package com.avecsys.quotemanager.validators;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.jsf.FacesContextUtils;

import com.avecsys.quotemanager.constants.ApplicationConstants;
import com.avecsys.quotemanager.exception.BusinessException;
import com.avecsys.quotemanager.service.buyer.BuyerMasterService;
import com.avecsys.quotemanager.utils.MessageBoardUtil;
import com.avecsys.quotemanager.utils.UIComponentUtils;
import com.avecsys.quotemanager.vo.BuyerVO;
import com.icesoft.faces.component.ext.HtmlInputHidden;

public class ValidatorBuyerEmailRegisteredCheck extends BaseValidator
{
	

	private static final Log log = LogFactory.getLog(ValidatorSupplierEmailRegisteredCheck.class);

	public FacesMessage validateFieldValue(FacesContext facesContext, UIComponent uIComponent,
			Object object) throws ValidatorException
	{
		String emailInputField = (String) object;
		BuyerMasterService buyerMasterService = (BuyerMasterService) FacesContextUtils.getWebApplicationContext(
				facesContext)
				.getBean("buyerMasterService");
		FacesMessage message = new FacesMessage();
		BuyerVO buyerVO = new BuyerVO();
		HtmlInputHidden uiComponentBuyerId = (HtmlInputHidden) uIComponent.getParent().findComponent(
				"buyerID");
		HtmlInputHidden uicomponentBuyerUserId = (HtmlInputHidden) uIComponent.getParent()
				.findComponent("buyerUserID");
		if (!UIComponentUtils.isValueEmpty(uiComponentBuyerId))
		{
			buyerVO.setBuyerId(new Long(uiComponentBuyerId.getValue().toString()));
		}
		if (!UIComponentUtils.isValueEmpty(uicomponentBuyerUserId))
		{
			buyerVO.setBuyerUserId(new Long(uicomponentBuyerUserId.getValue().toString()));
		}
		buyerVO.setDefaultAdminUserEmail(emailInputField);
		try
		{
			if (!buyerMasterService.isBuyerEmailNotRegistered(buyerVO))
			{
				message.setSummary(MessageBoardUtil.getValue(
						facesContext,
							ApplicationConstants.RESOURCE_BUNDLE_SUPPLIER,
							ApplicationConstants.VALIDATOR_ERROR_SUPPLIER_EMAIL_REGISTERED_ALREADY,
							null));
			}
		}
		catch (BusinessException e)
		{
			log.error(e);
		}
		return message;
	}


}
